import React, { useRef, useEffect, useState } from 'react';
import styled from '@emotion/styled';
import { useChat } from '../context/ChatContext';
import CodeBlock from './CodeBlock';
import { Input, Button, message, Tooltip } from 'antd';
import { 
  SendOutlined, 
  LoadingOutlined, 
  CopyOutlined, 
  CheckOutlined, 
  EditOutlined,
  InfoCircleOutlined,
  CloseOutlined
} from '@ant-design/icons';
import { keyframes } from '@emotion/react';

// Types for ChatContext
interface ChatMessage {
  id: string;
  role: 'user' | 'assistant';
  content: string;
  timestamp: number;
}

interface ChatSession {
  id: string;
  title: string;
  messages: ChatMessage[];
  createdAt: number;
  updatedAt: number;
}

// Animation keyframes
const fadeIn = keyframes`
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
`;

const slideIn = keyframes`
  from {
    opacity: 0;
    transform: translateX(10px);
  }
  to {
    opacity: 1;
    transform: translateX(0);
  }
`;

const pulse = keyframes`
  0% {
    transform: scale(1);
    opacity: 1;
  }
  50% {
    transform: scale(1.05);
    opacity: 0.8;
  }
  100% {
    transform: scale(1);
    opacity: 1;
  }
`;

// Main container
const ChatContainer = styled.div`
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #0f1117;
  position: relative;
`;

// Header styling
const ChatHeader = styled.div`
  padding: 14px 24px;
  background: #16171d;
  border-bottom: 1px solid rgba(255, 255, 255, 0.08);
  display: flex;
  align-items: center;
  justify-content: space-between;
  z-index: 10;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  height: 60px;
  backdrop-filter: blur(10px);
`;

const HeaderTitle = styled.h1`
  color: #fff;
  font-size: 18px;
  margin: 0;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 10px;
  
  &::before {
    content: '';
    display: block;
    width: 10px;
    height: 10px;
    border-radius: 50%;
    background: #10b981;
    box-shadow: 0 0 8px #10b981;
    animation: ${pulse} 2s infinite ease-in-out;
  }
`;

const HeaderActions = styled.div`
  display: flex;
  gap: 12px;
  align-items: center;
`;

const HeaderButton = styled(Button)`
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.8);
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 0;
  width: 32px;
  height: 32px;
  border-radius: 8px;
  
  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    color: #fff !important;
    border-color: rgba(255, 255, 255, 0.15) !important;
  }
`;

// Message list area
const MessageList = styled.div`
  flex: 1;
  overflow-y: auto;
  padding: 20px 0;
  scroll-behavior: smooth;
  background: linear-gradient(180deg, #0f1117 0%, #131620 100%);

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(0, 0, 0, 0.1);
  }

  &::-webkit-scrollbar-thumb {
    background: rgba(255, 255, 255, 0.2);
    border-radius: 3px;
    
    &:hover {
      background: rgba(255, 255, 255, 0.3);
    }
  }
`;

// Message container
const MessageContainer = styled.div`
  max-width: 900px;
  margin: 0 auto;
  padding: 0 24px;
`;

// Message group
const MessageGroup = styled.div`
  display: flex;
  flex-direction: column;
  gap: 2px;
  margin-bottom: 32px;
  animation: ${fadeIn} 0.3s ease-out;
`;

const DateDivider = styled.div`
  display: flex;
  align-items: center;
  justify-content: center;
  margin: 24px 0;
  
  &::before, &::after {
    content: '';
    height: 1px;
    background: rgba(255, 255, 255, 0.1);
    flex: 1;
  }
  
  span {
    color: rgba(255, 255, 255, 0.5);
    font-size: 12px;
    padding: 0 16px;
  }
`;

// Message bubble wrapper
const MessageBubbleWrapper = styled.div<{ role: 'user' | 'assistant' }>`
  position: relative;
  max-width: 85%;
  align-self: ${props => props.role === 'user' ? 'flex-end' : 'flex-start'};
  margin-top: 4px;

  &:hover .message-actions {
    opacity: 1;
  }
`;

// Message bubble
const MessageBubble = styled.div<{ role: 'user' | 'assistant' }>`
  background: ${props => props.role === 'user' 
    ? 'linear-gradient(135deg, #4a9eff 0%, #3b7fff 100%)' 
    : 'linear-gradient(135deg, #1e2030 0%, #252837 100%)'};
  color: ${props => props.role === 'user' ? '#fff' : '#e1e1e1'};
  padding: 14px 18px;
  border-radius: 18px;
  ${props => props.role === 'user' ? 'border-bottom-right-radius: 4px;' : 'border-bottom-left-radius: 4px;'}
  font-size: 15px;
  line-height: 1.6;
  box-shadow: ${props => props.role === 'user' 
    ? '0 2px 8px rgba(74, 158, 255, 0.3)' 
    : '0 2px 10px rgba(0, 0, 0, 0.15)'};
  border: 1px solid ${props => props.role === 'user' 
    ? 'rgba(74, 158, 255, 0.3)' 
    : 'rgba(255, 255, 255, 0.05)'};
  backdrop-filter: blur(4px);
  transition: transform 0.2s ease, box-shadow 0.2s ease;

  &:hover {
    box-shadow: ${props => props.role === 'user' 
      ? '0 4px 12px rgba(74, 158, 255, 0.4)' 
      : '0 4px 15px rgba(0, 0, 0, 0.2)'};
    transform: translateY(-1px);
  }

  pre {
    margin: 12px 0;
  }

  p {
    margin: 0 0 14px 0;
    white-space: pre-wrap;
  }
  
  p:last-of-type {
    margin-bottom: 0;
  }

  a {
    color: ${props => props.role === 'user' ? '#fff' : '#4a9eff'};
    text-decoration: underline;
    text-underline-offset: 2px;
    
    &:hover {
      opacity: 0.9;
    }
  }
`;

// Message actions container
const MessageActions = styled.div<{ role: 'user' | 'assistant' }>`
  position: absolute;
  ${props => props.role === 'user' ? 'left: -40px;' : 'right: -40px;'}
  top: 10px;
  display: flex;
  flex-direction: column;
  gap: 8px;
  opacity: 0;
  transition: opacity 0.2s;
  
  &.message-actions {
    opacity: 0;
  }
`;

// Action button
const ActionButton = styled(Button)<{ $copied?: boolean }>`
  min-width: 32px;
  height: 32px;
  padding: 0;
  border: 1px solid rgba(255, 255, 255, 0.1);
  background: ${props => props.$copied ? 'rgba(16, 185, 129, 0.2)' : 'rgba(255, 255, 255, 0.05)'};
  color: ${props => props.$copied ? '#10b981' : 'rgba(255, 255, 255, 0.8)'};
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  animation: ${slideIn} 0.2s ease;

  &:hover {
    background: ${props => props.$copied ? 'rgba(16, 185, 129, 0.3)' : 'rgba(255, 255, 255, 0.1)'} !important;
    color: ${props => props.$copied ? '#10b981' : '#fff'} !important;
    border-color: ${props => props.$copied ? 'rgba(16, 185, 129, 0.3)' : 'rgba(255, 255, 255, 0.15)'} !important;
    transform: translateY(-2px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.15);
  }

  .anticon {
    font-size: 14px;
  }
`;

// Message header
const MessageHeader = styled.div<{ role: 'user' | 'assistant' }>`
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
  ${props => props.role === 'user' ? 'justify-content: flex-end;' : 'justify-content: flex-start;'}
`;

// Avatar
const Avatar = styled.div<{ role: 'user' | 'assistant' }>`
  width: 32px;
  height: 32px;
  border-radius: 50%;
  background: ${props => props.role === 'user' ? 'linear-gradient(135deg, #4a9eff 0%, #3b7fff 100%)' : 'linear-gradient(135deg, #10b981 0%, #0ea271 100%)'};
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 14px;
  color: white;
  font-weight: 600;
  order: ${props => props.role === 'user' ? 1 : 0};
  box-shadow: ${props => props.role === 'user' 
    ? '0 2px 5px rgba(74, 158, 255, 0.3)' 
    : '0 2px 5px rgba(16, 185, 129, 0.3)'};
  border: 2px solid ${props => props.role === 'user' 
    ? 'rgba(74, 158, 255, 0.5)' 
    : 'rgba(16, 185, 129, 0.5)'};
`;

// Timestamp
const Timestamp = styled.span<{ role: 'user' | 'assistant' }>`
  color: rgba(255, 255, 255, 0.5);
  font-size: 12px;
  order: ${props => props.role === 'user' ? 0 : 1};
`;

// Input container
const InputContainer = styled.div`
  padding: 20px 24px 24px;
  background: #16171d;
  border-top: 1px solid rgba(255, 255, 255, 0.08);
  z-index: 10;
  box-shadow: 0 -2px 10px rgba(0, 0, 0, 0.1);
`;

// Input wrapper
const InputWrapper = styled.div`
  display: flex;
  gap: 12px;
  max-width: 900px;
  margin: 0 auto;
  position: relative;
`;

// Input text area
const StyledTextArea = styled(Input.TextArea)`
  background: rgba(255, 255, 255, 0.03) !important;
  border: 1px solid rgba(255, 255, 255, 0.1) !important;
  color: #fff !important;
  resize: none !important;
  padding: 14px 16px !important;
  border-radius: 16px !important;
  font-size: 15px !important;
  line-height: 1.6 !important;
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1) !important;
  transition: all 0.3s ease !important;
  
  &:hover {
    border-color: rgba(74, 158, 255, 0.5) !important;
    box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15) !important;
  }
  
  &:focus {
    border-color: rgba(74, 158, 255, 0.7) !important;
    box-shadow: 0 0 0 2px rgba(74, 158, 255, 0.1) !important;
    transform: translateY(-1px);
  }

  &::placeholder {
    color: rgba(255, 255, 255, 0.3) !important;
  }
`;

// Send button
const SendButton = styled(Button)`
  height: auto !important;
  padding: 14px !important;
  border-radius: 12px !important;
  background: linear-gradient(135deg, #4a9eff 0%, #3b7fff 100%) !important;
  border: none !important;
  box-shadow: 0 2px 8px rgba(74, 158, 255, 0.3) !important;
  transition: all 0.3s ease !important;
  
  &:hover {
    opacity: 0.9 !important;
    transform: translateY(-2px) !important;
    box-shadow: 0 4px 12px rgba(74, 158, 255, 0.4) !important;
  }
  
  &:active {
    transform: translateY(1px) !important;
    box-shadow: 0 1px 5px rgba(74, 158, 255, 0.3) !important;
  }
  
  .anticon {
    font-size: 18px;
  }
  
  &:disabled {
    opacity: 0.6 !important;
    cursor: not-allowed !important;
    transform: none !important;
  }
`;

// Character count
const CharCount = styled.div<{ almostFull: boolean }>`
  position: absolute;
  right: 55px;
  bottom: 8px;
  font-size: 12px;
  color: ${props => props.almostFull ? 'rgba(255, 152, 0, 0.8)' : 'rgba(255, 255, 255, 0.4)'};
  background: rgba(0, 0, 0, 0.2);
  padding: 2px 8px;
  border-radius: 10px;
  pointer-events: none;
  transition: all 0.3s ease;
  opacity: ${props => props.almostFull ? 1 : 0.7};
`;

// Loading container
const LoadingContainer = styled.div`
  display: flex;
  align-items: center;
  gap: 12px;
  color: rgba(255, 255, 255, 0.7);
  padding: 14px 18px;
  background: linear-gradient(135deg, #1e2030 0%, #252837 100%);
  border-radius: 18px;
  border-bottom-left-radius: 4px;
  margin-top: 4px;
  font-size: 15px;
  border: 1px solid rgba(255, 255, 255, 0.05);
  box-shadow: 0 2px 10px rgba(0, 0, 0, 0.15);
  max-width: 130px;
  animation: ${fadeIn} 0.3s ease-out;
  
  .anticon {
    color: #4a9eff;
  }
`;

// Welcome container for empty chats
const WelcomeContainer = styled.div`
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
  padding: 0 20px;
  text-align: center;
  animation: ${fadeIn} 0.5s ease-out;
`;

const WelcomeTitle = styled.h2`
  color: #fff;
  font-size: 24px;
  margin-bottom: 16px;
  font-weight: 500;
`;

const WelcomeText = styled.p`
  color: rgba(255, 255, 255, 0.7);
  font-size: 16px;
  max-width: 500px;
  margin-bottom: 32px;
  line-height: 1.6;
`;

const SuggestedQuestions = styled.div`
  display: flex;
  flex-wrap: wrap;
  justify-content: center;
  gap: 10px;
  max-width: 600px;
`;

const SuggestedQuestion = styled(Button)`
  background: rgba(255, 255, 255, 0.05);
  border: 1px solid rgba(255, 255, 255, 0.1);
  color: rgba(255, 255, 255, 0.9);
  border-radius: 12px;
  padding: 8px 16px;
  font-size: 14px;
  
  &:hover {
    background: rgba(255, 255, 255, 0.1) !important;
    color: #fff !important;
    border-color: rgba(255, 255, 255, 0.15) !important;
    transform: translateY(-2px);
  }
`;

const formatTime = (timestamp: number) => {
  return new Date(timestamp).toLocaleTimeString('zh-CN', {
    hour: '2-digit',
    minute: '2-digit'
  });
};

const formatDate = (timestamp: number) => {
  const date = new Date(timestamp);
  const today = new Date();
  const yesterday = new Date(today);
  yesterday.setDate(yesterday.getDate() - 1);
  
  if (date.toDateString() === today.toDateString()) {
    return '今天';
  } else if (date.toDateString() === yesterday.toDateString()) {
    return '昨天';
  } else {
    return date.toLocaleDateString('zh-CN', {
      year: 'numeric',
      month: 'long',
      day: 'numeric'
    });
  }
};

// 检测字符串是否包含代码块
const hasCodeBlock = (content: string) => {
  return content.includes('```');
};

// 解析消息内容，分离代码块和普通文本
const parseMessage = (content: string) => {
  const parts = [];
  const codeBlockRegex = /```(\w+)?\n([\s\S]*?)```/g;
  let lastIndex = 0;
  let match;

  while ((match = codeBlockRegex.exec(content)) !== null) {
    // 添加代码块前的文本
    if (match.index > lastIndex) {
      parts.push({
        type: 'text',
        content: content.slice(lastIndex, match.index)
      });
    }

    // 添加代码块
    parts.push({
      type: 'code',
      language: match[1] || 'text',
      content: match[2]
    });

    lastIndex = match.index + match[0].length;
  }

  // 添加剩余的文本
  if (lastIndex < content.length) {
    parts.push({
      type: 'text',
      content: content.slice(lastIndex)
    });
  }

  return parts;
};

// Format links in text
const formatLinks = (text: string) => {
  const linkRegex = /(https?:\/\/[^\s]+)/g;
  return text.replace(linkRegex, '<a href="$1" target="_blank" rel="noopener noreferrer">$1</a>');
};

const MessageContent: React.FC<{ content: string; role: 'user' | 'assistant' }> = ({ content, role }) => {
  if (hasCodeBlock(content)) {
    const parts = parseMessage(content);
    return (
      <>
        {parts.map((part: any, index: number) => (
          <React.Fragment key={index}>
            {part.type === 'text' && (
              <p dangerouslySetInnerHTML={{ __html: formatLinks(part.content.replace(/\n/g, '<br>')) }} />
            )}
            {part.type === 'code' && (
              <CodeBlock code={part.content} language={part.language} />
            )}
          </React.Fragment>
        ))}
      </>
    );
  }

  return <p dangerouslySetInnerHTML={{ __html: formatLinks(content.replace(/\n/g, '<br>')) }} />;
};

// Mock suggestions for empty state
const suggestedQuestions = [
  '请帮我解释一下什么是React钩子?',
  '如何在TypeScript中使用泛型?',
  '请告诉我如何优化网站性能',
  '写一个简单的Docker配置文件',
  '帮我设计一个Todo应用的组件结构'
];

export const Chat: React.FC = () => {
  // Using any type temporarily to fix the linter errors
  const { messages = [], addMessage, isAiTyping = false, currentInput = '', setCurrentInput } = useChat() as any;
  const [messageCopied, setMessageCopied] = useState<string | null>(null);
  const messagesEndRef = useRef<HTMLDivElement>(null);
  const textAreaRef = useRef<any>(null);
  const MAX_CHARS = 4000;

  const scrollToBottom = () => {
    if (messagesEndRef.current) {
      messagesEndRef.current.scrollIntoView({ behavior: 'smooth' });
    }
  };

  useEffect(() => {
    scrollToBottom();
  }, [messages, isAiTyping]);

  const handleSubmit = async (e: React.KeyboardEvent) => {
    if (e.key === 'Enter' && !e.shiftKey) {
      e.preventDefault();
      if (currentInput.trim() && !isAiTyping && currentInput.length <= MAX_CHARS) {
        await addMessage('user', currentInput);
        setCurrentInput('');
        
        // Simulate AI response
        setTimeout(() => {
          addMessage('assistant', '这是一个模拟的AI回复，展示代码块功能:\n\n```typescript\nconst greeting = (name: string): string => {\n  return `Hello, ${name}!`;\n};\n\nconsole.log(greeting("World"));\n```\n\n您可以继续发送消息来测试界面。');
        }, 1500);
        
        if (textAreaRef.current) {
          textAreaRef.current.focus();
        }
      }
    }
  };

  const handleSendClick = async () => {
    if (currentInput.trim() && !isAiTyping && currentInput.length <= MAX_CHARS) {
      await addMessage('user', currentInput);
      setCurrentInput('');
      
      // Simulate AI response
      setTimeout(() => {
        addMessage('assistant', '这是一个模拟的AI回复，展示代码块功能:\n\n```typescript\nconst greeting = (name: string): string => {\n  return `Hello, ${name}!`;\n};\n\nconsole.log(greeting("World"));\n```\n\n您可以继续发送消息来测试界面。');
      }, 1500);
      
      if (textAreaRef.current) {
        textAreaRef.current.focus();
      }
    }
  };

  const handleCopyMessage = (messageId: string, content: string) => {
    navigator.clipboard.writeText(content).then(() => {
      setMessageCopied(messageId);
      setTimeout(() => setMessageCopied(null), 2000);
    });
  };

  const handleSuggestedQuestion = (question: string) => {
    setCurrentInput(question);
    if (textAreaRef.current) {
      textAreaRef.current.focus();
    }
  };

  // Group messages by date
  const groupedMessages = messages.reduce((groups: any, message: any) => {
    const date = formatDate(message.timestamp);
    if (!groups[date]) {
      groups[date] = [];
    }
    groups[date].push(message);
    return groups;
  }, {});

  return (
    <ChatContainer>
      <ChatHeader>
        <HeaderTitle>AI 对话</HeaderTitle>
        <HeaderActions>
          <Tooltip title="帮助">
            <HeaderButton icon={<InfoCircleOutlined />} />
          </Tooltip>
          <Tooltip title="清除会话">
            <HeaderButton icon={<CloseOutlined />} />
          </Tooltip>
        </HeaderActions>
      </ChatHeader>
      
      <MessageList>
        {messages.length === 0 ? (
          <WelcomeContainer>
            <WelcomeTitle>欢迎使用AI助手</WelcomeTitle>
            <WelcomeText>
              您可以向我询问任何问题，我会尽力提供帮助。无论是编程问题、知识咨询，还是创意想法，请随时开始对话。
            </WelcomeText>
            <SuggestedQuestions>
              {suggestedQuestions.map((question, index) => (
                <SuggestedQuestion 
                  key={index} 
                  onClick={() => handleSuggestedQuestion(question)}
                >
                  {question}
                </SuggestedQuestion>
              ))}
            </SuggestedQuestions>
          </WelcomeContainer>
        ) : (
          <MessageContainer>
            {Object.entries(groupedMessages).map(([date, dateMessages]: [string, any]) => (
              <React.Fragment key={date}>
                <DateDivider><span>{date}</span></DateDivider>
                {dateMessages.map((msg: any, index: number) => (
                  <MessageGroup key={`${msg.id}-${index}`}>
                    <MessageHeader role={msg.role}>
                      <Avatar role={msg.role}>
                        {msg.role === 'user' ? 'U' : 'AI'}
                      </Avatar>
                      <Timestamp role={msg.role}>
                        {formatTime(msg.timestamp)}
                      </Timestamp>
                    </MessageHeader>
                    
                    <MessageBubbleWrapper role={msg.role}>
                      <MessageBubble role={msg.role}>
                        <MessageContent content={msg.content} role={msg.role} />
                      </MessageBubble>
                      
                      <MessageActions role={msg.role} className="message-actions">
                        <Tooltip title="复制内容">
                          <ActionButton 
                            icon={messageCopied === msg.id ? <CheckOutlined /> : <CopyOutlined />} 
                            onClick={() => handleCopyMessage(msg.id, msg.content)}
                            $copied={messageCopied === msg.id}
                          />
                        </Tooltip>
                        {msg.role === 'user' && (
                          <Tooltip title="编辑并重新发送">
                            <ActionButton 
                              icon={<EditOutlined />} 
                              onClick={() => setCurrentInput(msg.content)}
                            />
                          </Tooltip>
                        )}
                      </MessageActions>
                    </MessageBubbleWrapper>
                  </MessageGroup>
                ))}
              </React.Fragment>
            ))}
            
            {isAiTyping && (
              <LoadingContainer>
                <LoadingOutlined style={{ fontSize: 16 }} />
                思考中...
              </LoadingContainer>
            )}
            
            <div ref={messagesEndRef} />
          </MessageContainer>
        )}
      </MessageList>
      
      <InputContainer>
        <InputWrapper>
          <StyledTextArea
            ref={textAreaRef}
            value={currentInput}
            onChange={e => setCurrentInput(e.target.value)}
            onKeyDown={handleSubmit}
            placeholder="输入消息，按Enter发送，Shift+Enter换行..."
            autoSize={{ minRows: 1, maxRows: 6 }}
            disabled={isAiTyping}
            maxLength={MAX_CHARS}
          />
          {currentInput.length > 0 && (
            <CharCount almostFull={currentInput.length > MAX_CHARS * 0.8}>
              {currentInput.length}/{MAX_CHARS}
            </CharCount>
          )}
          <SendButton
            type="primary"
            icon={<SendOutlined />}
            onClick={handleSendClick}
            disabled={!currentInput.trim() || isAiTyping || currentInput.length > MAX_CHARS}
          />
        </InputWrapper>
      </InputContainer>
    </ChatContainer>
  );
}; 